package com.qf.ssm.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.ssm.cache.AreasCache;
import com.qf.ssm.cache.CategoriesCache;
import com.qf.ssm.dto.ResultCode;
import com.qf.ssm.event.ColorCommandEvent;
import com.qf.ssm.event.PowerCommandEvent;
import com.qf.ssm.event.UpdateDevicesStatusEvent;
import com.qf.ssm.exceptions.AddErrorException;
import com.qf.ssm.exceptions.DeleteErrorException;
import com.qf.ssm.exceptions.MybaseException;
import com.qf.ssm.exceptions.UpdateErrorException;
import com.qf.ssm.mapper.DevicesMapper;
import com.qf.ssm.pojo.CheckStatus;
import com.qf.ssm.pojo.Devices;
import com.qf.ssm.service.DevicesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service
@Transactional
public class DevicesServiceImpl implements DevicesService {

    private DevicesMapper devicesMapper;

    private AreasCache areasCache;

    @Autowired
    public void setAreasCache(AreasCache areasCache) {
        this.areasCache = areasCache;
    }

    private CategoriesCache categoriesCache;

    @Autowired
    public void setCategoriesCache(CategoriesCache categoriesCache) {
        this.categoriesCache = categoriesCache;
    }

    @Autowired
    public void setDevicesMapper(DevicesMapper devicesMapper) {
        this.devicesMapper = devicesMapper;
    }

    @Autowired
    public ApplicationContext context;

    @Override
    public void addDevices(Devices devices) {
        if (devices.isNull(CheckStatus.ADD)) {
            throw new AddErrorException("添加的数据不能为空", ResultCode.DATA_NOT_ALLOW_NUL);
        }
        try {
            devicesMapper.addDevices(devices);
        } catch (Exception e) {
            e.printStackTrace();
            throw new AddErrorException("添加失败", ResultCode.ERROR);
        }

    }
    @Override
    public int deleteDevicesByIds(Long[] ids) {
        if(ids==null || ids.length==0){
            //删除时必须又id
            throw  new DeleteErrorException("删除必须传递 id", ResultCode.DATA_NOT_ALLOW_NUL);
        }
        return devicesMapper.deleteDevicesByIds(Arrays.asList(ids));
    }

    @Override
    public void updateDevices(Devices devices) {
        if (devices == null || devices.isNull(CheckStatus.UPDATE)) {
            throw new UpdateErrorException("数据为空", ResultCode.DATA_NOT_ALLOW_NUL);
        }
        try {
            devicesMapper.updateDevices(devices);
        } catch (Exception e) {
            e.printStackTrace();
            throw new UpdateErrorException("更新失败", ResultCode.ERROR);
        }
    }


    @Override
    public PageInfo<Devices> getAllDevices(int pageNum, int pageSize, String address, int status, int direction, int areaid, int categoryid) {
        PageHelper.startPage(pageNum, pageSize);
        try {


            List<Devices> devicesList = devicesMapper.getAllDevices(address, status, direction, areaid, categoryid);
            //我们上面查询的数据中没有分类信息,需要设置
            //分类信息在缓存中,直接查缓存就可以
            //每个设备的分类可能不一样,怎么知道哪个分类
            devicesList.forEach(devices -> {
                devices.setCategory(categoriesCache.get(devices.getCategoryid()));
                devices.setAreaname(areasCache.get(devices.getAreaid()).getAreaname());
                devices.setCategoryname(categoriesCache.get(devices.getCategoryid()).getCategoryname());
            });
            return new PageInfo<>(devicesList);

        }catch (Exception e){
            e.printStackTrace();
            throw new MybaseException("查询异常", ResultCode.ERROR);
        }

    }

    @Override
    public Devices getDevicesById(Long id) {
        if (id == null || id == 0) {
            throw new MybaseException("数据为空", ResultCode.DATA_NOT_ALLOW_NUL);
        }

        try {
            Devices device = devicesMapper.getDeviceById(id);
            if (device == null) {
                throw new MybaseException("查询失败", ResultCode.ERROR);
            }

            return device;
        } catch (Exception e) {
            e.printStackTrace();
            throw new MybaseException("查询失败", ResultCode.ERROR);

        }
    }

    @Override
    public Devices getDevicesByUUId(String uuid) {
        if (StringUtils.isEmpty(uuid)) {
            throw new MybaseException("数据为空", ResultCode.DATA_NOT_ALLOW_NUL);
        }

        Devices device = devicesMapper.getDeviceByUUId(uuid);
        return device;
    }

    @Override
    public void sendCommand(String uuid, String command) {
        //根据标识找到设备的会话
        String value = null;
        switch (command) {

            case "open":
                value = "0";
                break;
            case "close":
                value = "1";
                break;
            case "change":
                value = "2";
                context.publishEvent(new ColorCommandEvent(uuid, value));
                return;
        }

        //通过会话将指令发送出去
        System.err.println(Thread.currentThread().getName());
        context.publishEvent(new PowerCommandEvent(uuid, value));
    }
    @Override
    public void updateStatus(String uuid, String status) {
        devicesMapper.updateOffLine(uuid, status);
    }

    @Override
    public void onEvent(UpdateDevicesStatusEvent event) {
        updateStatus(event.getUuid(), event.getStatus());
    }
}



